package com.hqyj.paimaisys.controller;


import com.hqyj.paimaisys.model.Admin;
import com.hqyj.paimaisys.service.AdminService;
import com.hqyj.paimaisys.util.TokenUtil;
import com.hqyj.paimaisys.web.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${accessTokenExpireTime}")
    private long accessTokenExpireTime;

    //管理员登录
    @RequestMapping("/login")
    public ResponseResult<String> login(@RequestBody Admin admin) throws Exception {
        System.out.println(admin);
       //分三种情况，
        Admin admindb = adminService.getById(admin.getAid());

        if(admindb == null){
            return ResponseResult.error("管理员账号错误");
        }
        if(!admin.getApwd().equals(admindb.getApwd())){
            return ResponseResult.error("管理员密码错误");
        }

        //用户名和密码都对。 生成token,保存到redis中
        String token = TokenUtil.sign(admin.getAid());

        stringRedisTemplate.opsForValue().set(token, admin.getAid(),accessTokenExpireTime, TimeUnit.SECONDS);

        return ResponseResult.success(token);
    }

}

